class WsClientPool {
    constructor(app) {
        this.app = app;
        this.log = app.log.getLogger('wspool');

        this.clientMap = {};
        this.cid2ClientId = {};
        this.clientId2Cid = {};

        this.clientKillMap = {};
    }

    get(cid) {
        const clientId = this.cid2ClientId[cid];
        let client = null;

        if (clientId && clientId in this.clientMap) {
            client = this.clientMap[clientId];
        }
        return client;
    }

    add(client) {
        let memo = '';
        if (client.cid in this.cid2ClientId) {
            // 获取 旧 client
            const oldClientId = this.cid2ClientId[client.cid];
            const oldClient = this.clientMap[oldClientId];

            delete this.clientId2Cid[client.cid];
            delete this.cid2ClientId[oldClientId];
            delete this.clientMap[oldClientId];

            // 添加 client kill 表
            this.clientKillMap[oldClientId] = oldClient;

            // 关闭
            oldClient.close(1001, `connection exsit ${oldClientId}`);

            this.log.info('[add] recover: cid: %s, oldClientId: %s, newCliendId: %s',
                client.cid, oldClientId, client.id);
            memo = 'cover';
        }

        this.clientId2Cid[client.id] = client.cid;
        this.cid2ClientId[client.cid] = client.id;
        this.clientMap[client.id] = client;

        if (memo === '') {
            this.log.info('[add] success: cid = %s, clientId = %s', client.cid, client.id);
        }
    }
    del(ws) {
        if (!(ws.id in this.clientKillMap)) {
            const cid = this.clientId2Cid[ws.id];
            const client = this.clientMap[ws.id];

            if (!client) { return; }

            delete this.cid2ClientId[cid];
            delete this.clientId2Cid[ws.id];
            delete this.clientMap[ws.id];

            this.log.info('[del] success: cid: %s, clientId: %s', cid, client.id);
        } else {
            delete this.clientKillMap[ws.id];
            this.log.info('[del] repeat: clientId: %s', ws.id);
        }
    }
}

export default WsClientPool;
